package com.xiaocikuai.smallchunks.mapper.Recode;

import com.xiaocikuai.smallchunks.entity.Card.CardChunks;
import com.xiaocikuai.smallchunks.entity.Recode.Recode;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.*;

@Mapper
public interface RecodeMapper {
    @Insert("INSERT INTO recode ( uid, cid, correct, time, level ,review ,pid) " +
            "VALUES ( #{uid}, #{cid}, #{correct}, #{time}, #{level}, #{review}, #{pid})")
    boolean recodeAdd(Recode recode);


    @Select("SELECT * FROM recode WHERE uid = #{uid} AND cid = #{cid}")
    ArrayList<Recode> getRecodeList(int uid, int cid);

    @Select("SELECT COUNT(*) FROM recode WHERE time = #{time} ")
    Integer isToday( Date time);

    @Select("SELECT * FROM recode WHERE uid = #{uid} AND cid = #{cid} ORDER BY time DESC LIMIT 1 ")
    Recode getRecode( int uid, int cid);

    @Select("SELECT COUNT(*) FROM recode WHERE uid = #{uid} AND cid = #{cid} ")
    int isNew( int uid, int cid);

//    @Select("SELECT correct FROM recode WHERE uid = #{uid} AND cid = #{cid}")
//    int isCorrect( int uid, int cid);

    @Select("SELECT level FROM recode WHERE uid = #{uid} AND cid = #{cid} ORDER BY time DESC LIMIT 1")
    int getLevel( int uid, int cid);

    @Update("UPDATE recode SET  correct = #{correct}, time = #{time}, level = #{level}, pid = #{pid} ,review = #{review} WHERE uid = #{uid} AND cid = #{cid} ")
    boolean recodeUpdate(Recode recode);


    @Select("SELECT COUNT(*) FROM recode WHERE uid = #{uid} AND cid = #{cid} AND time = #{time}")
    Integer getRecodeCount(int uid, int cid, Date time);


    @Select("SELECT correct FROM recode WHERE uid = #{uid} AND cid = #{cid} ORDER BY time DESC LIMIT 1")
    Integer isCorrect( int cid,int uid);



    @Select("SELECT correct FROM recode WHERE uid = #{uid} AND cid = #{cid} and time = #{time} ")
    Integer isCorrectd(int cid, int uid, LocalDate time);


    @Select("SELECT * FROM ( SELECT * From recode WHERE uid = #{uid} ORDER BY time DESC group by cid) as recard  review <= #{time} ")
    List<Recode> getRecodeForReview(int uid, LocalDate time );

    @Select("SELECT r.* FROM recode r INNER JOIN " +
            "(SELECT cid, MAX(time) as max_time FROM recode WHERE uid = #{uid} AND pid = #{pid} GROUP BY cid)" +
            " as latest ON r.cid = latest.cid AND r.time = latest.max_time WHERE r.review <= #{time}")
    List<Recode> getRecodeForReviewById(int uid, LocalDate time, int pid);
//    @Select({"SELECT cid  FROM  WHERE cid IN (#{recodeList}) AND uid = #{uid}"})
//    Map<Integer, Integer> getCorrectMap(@Param("recodeList") List<Integer> recodeList, @Param("uid") int uid);

    @Select("SELECT * FROM card_chunks WHERE  product_id = #{pid} ORDER BY RAND() LIMIT ${num}")
    List<CardChunks> getRandomList( int pid, String num);


}
